package com.wugh.fast.module.mapper.filter;

import com.wugh.fast.module.mapper.DynamicSchemaStorage;
import com.wugh.fast.module.mapper.service.DynamicSchemaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 说明:
 *
 * @author wugh
 * @date 2018-12-03 09:07
 */
@Slf4j
//@WebFilter
public class DynamicSchemaFilter extends OncePerRequestFilter {
    private DynamicSchemaService dynamicSchemaService;

    public DynamicSchemaFilter(DynamicSchemaService dynamicSchemaService) {
        this.dynamicSchemaService = dynamicSchemaService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            try {
                String schema = dynamicSchemaService.obtainSchema(request);
                if (StringUtils.isNotBlank(schema)) {
                    DynamicSchemaStorage.set(schema);
                }
            } catch (Exception e) {
                log.info("设置动态Schema失败:{}", e.getMessage());
            }
            filterChain.doFilter(request, response);
        } finally {
            try {
                DynamicSchemaStorage.clear();
            } catch (Exception e) {
                log.info("动态Schema状态清空失败失败:{}", e.getMessage());
            }
        }
    }
}
